/*
 * Copyright        : Copyright (c) 2011 Hegaka
 * Author           : Jon Arrien
 * Twitter          : @jonarrien
 * All right reserved
 */


#import <QuartzCore/QuartzCore.h>
#import "GalleryScrollView.h"
#import "GalleryButton.h"

@implementation GalleryScrollView


@synthesize delegate;
@synthesize mainView;
@synthesize attachments = _attachments;


int padding = 3;


#pragma mark - INIT

- (id) init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        ;
    }
    return self;
}

- (void) awakeFromNib
{
    // INIT ATTACHMENT ARRAY
    if (_attachments == nil){
        _attachments = [[NSMutableArray alloc] init];
    }

    // SCROLL VIEW
    UIScrollView *scrollTemp = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 80)];
    _scrollView = scrollTemp;
    _scrollView.backgroundColor = [UIColor clearColor];

    [self addSubview:_scrollView];
    [scrollTemp release];
}


- (void) dealloc {
    [super dealloc];

}


#pragma mark - ATTACHMENTS ADD / REMOVE

- (void) addAttachment:(AttachmentItem *)attachment
{
    // SAVE ATTACHMENT
    [_attachments addObject:attachment];

    // RESIZE CONTENT VIEW FOR INSERTINT NEW ATTACHMENT
    _scrollView.contentSize = CGSizeMake([_attachments count]*70, 70);

    CGFloat startX = (70.0f * ((float)[_attachments count] - 1.0f) + padding);
    CGFloat startY = padding;
    CGFloat width = 64;
    CGFloat height = 64;

    GalleryButton *btnAttachment = [[GalleryButton alloc] initWithFrame:CGRectMake(startX, startY, width, height)];
    btnAttachment.tag = [_attachments count];
    btnAttachment.scrollParent = _scrollView;
    btnAttachment.mainView = self.mainView;
    btnAttachment.delegate = self;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 64)];
    imageView.image=attachment.image;
    [btnAttachment addSubview:imageView];
    [imageView release];
    [_scrollView addSubview:btnAttachment];
    [btnAttachment release];

}
#pragma mark - RELOAD DATA

- (void) reloadData
{
    for (UIView *vi in _scrollView.subviews){
        [vi removeFromSuperview];
    }

    for (int i=0; i<[_attachments count] ; i++) {
        AttachmentItem *item = [_attachments objectAtIndex:i];
        _scrollView.contentSize = CGSizeMake([_attachments count]*70, 70);

        CGFloat startX = (70.0f * i) + padding;
        CGFloat startY = padding;
        CGFloat width = 64;
        CGFloat height = 64;

        GalleryButton *btnAttachment = [[GalleryButton alloc] initWithFrame:CGRectMake(startX, startY, width, height)];
        btnAttachment.tag = [_attachments count];
        btnAttachment.scrollParent = _scrollView;
        btnAttachment.mainView = self.mainView;
        btnAttachment.delegate = self;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 64)];
        imageView.image=item.image;
        [btnAttachment addSubview:imageView];
        [imageView release];
        [_scrollView addSubview:btnAttachment];
        [btnAttachment release];

    }

}


#pragma mark - GALLERY BUTTON DELEGATE

-(void) touchDown
{
//    [self.delegate didPressButton];
}

-(void) touchUp
{
//    [self.delegate didDropButton];
    _scrollView.scrollEnabled = YES;
}

-(BOOL) checkConflictWithOtherButton:(GalleryButton *)button inView:(UIScrollView *)scrollView{
    NSLog(@"button position: %f/%f",button.center.x,button.center.y);
    NSMutableArray *conflictButtons=[self getConflictButtons:button inView:scrollView];
    NSLog(@"Conflict buttons zise: %i",[conflictButtons count]);
    if ([conflictButtons count]==0) {
        return NO;
    }
    GalleryButton *conflictButton=[conflictButtons lastObject];
    int position;
    if (button.center.x>conflictButton.center.x) {
        position=[self getPositionOfGalleryButton:conflictButton isMoveButton:NO]+1;;
    } else {
        position= [self getPositionOfGalleryButton:conflictButton isMoveButton:NO];
    }
    if ([self insertView:button atIndex:position]) {
        return YES;
    }
    return NO;
}
-(NSMutableArray*)getConflictButtons:(GalleryButton*)button inView:(UIScrollView*) scrollView{
    NSMutableArray *arr=[[NSMutableArray alloc ] init];
    for (GalleryButton *buttonGallery in [scrollView subviews]) {
                CGPoint newLoc = [self convertPoint:buttonGallery.frame.origin toView:self.mainView];
                 CGRect binFrame = button.frame;
                   binFrame.origin = newLoc;
              if (CGRectIntersectsRect(binFrame, button.frame) == TRUE){
                  NSLog(@"Conflict button tag: %i",buttonGallery.tag);
                  [arr addObject:buttonGallery];
              }
    }
    if ([arr count]==0) {
        NSLog(@"There are no conflict here");
        return arr;
    } else {
        NSMutableArray *arr2 = [NSMutableArray arrayWithArray:[arr sortedArrayUsingComparator: ^(id a, id b) {
            GalleryButton *first = ( GalleryButton* ) a;
            GalleryButton *second = ( GalleryButton* ) b;
            if ( first.center.x == second.center.x)
                return NSOrderedSame;
            else if ( first.center.x < second.center.x )
                return NSOrderedAscending;
            else
                return NSOrderedDescending;
            
        }]];
        return arr2;
    }    
}
-(BOOL) insertView:(GalleryButton *)button atIndex:(NSInteger)position{
    int moveButtonPosition=[self getPositionOfGalleryButton:button isMoveButton:YES];
//    if (moveButtonPosition==position-1||moveButtonPosition==position) {
//        return NO;
//    }else
    if (moveButtonPosition>position){
        // MOVE THE OTHERS BUTTON TO RIGHT
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.7];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:_scrollView cache:YES];
        //    // ARRAY FOR SAVING THE ONES WE NEED
        NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[_attachments count]];
        GalleryButton *moveButton=[_attachments objectAtIndex:moveButtonPosition];
        
        for (int i=0; i<position; i++) {
            [itemsToKeep addObject:[_attachments objectAtIndex:i]];
        }
        [itemsToKeep addObject:moveButton];

        for (int j=position;j<[_attachments
                               count] ;j++ ) {
            if (j!=moveButtonPosition) {
                [itemsToKeep addObject:[_attachments objectAtIndex:j]];
            }
        }
        [_attachments removeAllObjects];
        [_attachments setArray:itemsToKeep];
        //
        //    // REMOVE THE BUTTON
        [button removeFromSuperview];
        [self reloadData];
        
        [UIView commitAnimations];
        return YES;
        
    } else if (moveButtonPosition<position){
        // MOVE THE OTHERS BUTTON TO LEFT
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.7];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:_scrollView cache:YES];
        //    // ARRAY FOR SAVING THE ONES WE NEED
        NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[_attachments count]];
        GalleryButton *moveButton=[_attachments objectAtIndex:moveButtonPosition];
        
        for (int i=0; i<position; i++) {
            if (i!=moveButtonPosition) {
                [itemsToKeep addObject:[_attachments objectAtIndex:i]];

            }
        }
        [itemsToKeep addObject:moveButton];
        
        for (int k=position; k<[_attachments count]; k++) {
            [itemsToKeep addObject:[_attachments objectAtIndex:k]];

        }
        [_attachments removeAllObjects];
        [_attachments setArray:itemsToKeep];
        // REMOVE THE BUTTON
        [button removeFromSuperview];
        [self reloadData];
        
        [UIView commitAnimations];
        return YES;
    }
    return NO;
}
-(int) getPositionOfGalleryButton:(GalleryButton *)button isMoveButton:(BOOL)isMove{
    int position;
    if (isMove) {
        position = (button.originalPosition.x - 35) / 70;
    } else {
        position = (button.center.x - 35) / 70;
    }
    return position;
}
//- ( GalleryButton *) getTheNearestButtonWith:(GalleryButton*) button inView:(UIScrollView *)scrollView{
////    NSArray *views=[scrollView subviews];
//    
//    return nil;
//    
//}
@end
